package com.LeeCode;

/**
 * 删除二叉搜索树中的节点
 */

public class Code450 {
    public static void main(String[] args) {

    }

    public TreeNode deleteNode(TreeNode root, int key) {
        if (root == null) return null;
        if (key < root.val) {
            root.left = deleteNode(root.left, key);
        } else if (key > root.val) {
            root.right = deleteNode(root.right, key);
        } else { // 找到了要删除节点
            if (root.left == null) return root.right;
            if (root.right == null) return root.left;

            int minVal = findNode(root.right);
            root.val = minVal;
            root.right = deleteNode(root.right, minVal);
        }
        return root;
    }

    private int findNode(TreeNode root) {
        while (root.left != null) {
            root = root.left;
        }
        return root.val;
    }
}
